<template>
  <Layout>
    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="px-6 py-4 border-b">
          <h1 class="text-2xl font-bold text-gray-900">我的收藏</h1>
          <p class="mt-1 text-sm text-gray-600">共收藏了 {{ total }} 篇文章</p>
        </div>

        <!-- 搜索栏 -->
        <div class="px-6 py-4 border-b bg-gray-50">
          <div class="relative">
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索收藏的文章..."
              class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            />
            <svg class="absolute left-3 top-2.5 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </div>
        </div>

        <!-- 收藏列表 -->
        <div>
          <div v-if="loading" class="py-12 text-center">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <p class="mt-2 text-gray-500">加载中...</p>
          </div>

          <div v-else-if="favorites.length === 0" class="py-12 text-center">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
            </svg>
            <p class="mt-2 text-gray-500">还没有收藏任何文章</p>
            <Link href="/" class="mt-4 inline-block text-blue-600 hover:text-blue-800">
              去发现好文章
            </Link>
          </div>

          <div v-else class="divide-y divide-gray-200">
            <article
              v-for="item in filteredFavorites"
              :key="item.id"
              class="p-6 hover:bg-gray-50 transition-colors"
            >
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <!-- 文章标题 -->
                  <h2 class="text-lg font-semibold text-gray-900 mb-2">
                    <Link :href="`/posts/${item.post.slug}`" class="hover:text-blue-600">
                      {{ item.post.title }}
                    </Link>
                  </h2>

                  <!-- 文章元信息 -->
                  <div class="flex items-center text-sm text-gray-500 space-x-4 mb-2">
                    <Link :href="`/profile/${item.post.user.username}`" class="flex items-center hover:text-gray-700">
                      <img
                        :src="item.post.user.avatar || `https://ui-avatars.com/api/?name=${item.post.user.name}&size=100`"
                        :alt="item.post.user.name"
                        class="w-5 h-5 rounded-full mr-1"
                      />
                      {{ item.post.user.name }}
                    </Link>
                    <span>{{ formatDate(item.post.published_at) }}</span>
                    <span v-if="item.post.category">
                      <Link :href="`/categories/${item.post.category.slug}`" class="hover:text-gray-700">
                        {{ item.post.category.name }}
                      </Link>
                    </span>
                    <span>{{ item.post.reading_time }} 分钟阅读</span>
                  </div>

                  <!-- 文章摘要 -->
                  <p class="text-gray-600 text-sm line-clamp-2 mb-3">
                    {{ item.post.excerpt || stripHtml(item.post.content).substring(0, 150) }}...
                  </p>

                  <!-- 标签 -->
                  <div v-if="item.post.tags && item.post.tags.length > 0" class="flex flex-wrap gap-2 mb-3">
                    <Link
                      v-for="tag in item.post.tags"
                      :key="tag.id"
                      :href="`/tags/${tag.slug}`"
                      class="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs hover:bg-gray-200"
                    >
                      {{ tag.name }}
                    </Link>
                  </div>

                  <!-- 统计信息和操作 -->
                  <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-4 text-sm text-gray-500">
                      <span class="flex items-center">
                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                        {{ item.post.views_count }}
                      </span>
                      <span class="flex items-center">
                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                        </svg>
                        {{ item.post.likes_count }}
                      </span>
                      <span class="flex items-center">
                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                        </svg>
                        {{ item.post.comments_count }}
                      </span>
                      <span class="text-gray-400">
                        收藏于 {{ formatDate(item.created_at) }}
                      </span>
                    </div>

                    <button
                      @click="removeFavorite(item)"
                      class="px-3 py-1 text-sm bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300"
                    >
                      取消收藏
                    </button>
                  </div>
                </div>

                <!-- 特色图片 -->
                <div v-if="item.post.featured_image" class="ml-6 flex-shrink-0">
                  <img
                    :src="`/storage/${item.post.featured_image}`"
                    :alt="item.post.title"
                    class="w-32 h-24 object-cover rounded-lg"
                  />
                </div>
              </div>
            </article>
          </div>

          <!-- 分页 -->
          <div v-if="totalPages > 1" class="px-6 py-4 border-t">
            <div class="flex justify-center">
              <nav class="flex space-x-2">
                <button
                  @click="currentPage--"
                  :disabled="currentPage === 1"
                  class="px-3 py-1 rounded-md border border-gray-300 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  上一页
                </button>
                <button
                  v-for="page in visiblePages"
                  :key="page"
                  @click="currentPage = page"
                  :class="currentPage === page ? 'bg-blue-600 text-white' : 'border border-gray-300 text-gray-700 hover:bg-gray-50'"
                  class="px-3 py-1 rounded-md text-sm"
                >
                  {{ page }}
                </button>
                <button
                  @click="currentPage++"
                  :disabled="currentPage === totalPages"
                  class="px-3 py-1 rounded-md border border-gray-300 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  下一页
                </button>
              </nav>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Link } from '@inertiajs/inertia-vue3'
import Layout from '@/Components/Layout.vue'
import axios from 'axios'

const loading = ref(false)
const favorites = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const perPage = 20
const total = ref(0)

// 筛选后的收藏
const filteredFavorites = computed(() => {
  if (!searchQuery.value) {
    return favorites.value
  }

  const query = searchQuery.value.toLowerCase()
  return favorites.value.filter(item => {
    const post = item.post
    return post.title.toLowerCase().includes(query) ||
           (post.excerpt && post.excerpt.toLowerCase().includes(query)) ||
           post.content.toLowerCase().includes(query) ||
           (post.user && post.user.name.toLowerCase().includes(query))
  })
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / perPage)
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 去除HTML标签
const stripHtml = (html) => {
  const tmp = document.createElement('div')
  tmp.innerHTML = html
  return tmp.textContent || tmp.innerText || ''
}

// 加载收藏列表
const loadFavorites = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/user/favorites', {
      params: {
        page: currentPage.value,
        per_page: perPage,
      }
    })

    favorites.value = response.data.favorites
    total.value = response.data.pagination.total
  } catch (error) {
    console.error('加载收藏失败:', error)
  } finally {
    loading.value = false
  }
}

// 取消收藏
const removeFavorite = async (item) => {
  if (!confirm('确定要取消收藏这篇文章吗？')) return

  try {
    await axios.post(`/api/posts/${item.post.id}/favorite`)

    // 从列表中移除
    const index = favorites.value.findIndex(f => f.id === item.id)
    if (index > -1) {
      favorites.value.splice(index, 1)
      total.value--
    }
  } catch (error) {
    console.error('取消收藏失败:', error)
  }
}

// 监听页码变化
watch(currentPage, () => {
  loadFavorites()
})

// 监听搜索
watch(searchQuery, () => {
  currentPage.value = 1
})

onMounted(() => {
  loadFavorites()
})
</script>